package com.mccken.practice;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 基于AQS实现的锁
 * 
 * 实现Lock接口，跟继承AQS的类做组合
 *
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2023-12-06 17:03
 **/
public class MyLock03 implements Lock {

	// 实现一个独占同步器
	class Syn extends AbstractQueuedSynchronizer {

		@Override
		protected boolean tryAcquire(int arg) {
			if (compareAndSetState(0, arg)) {
				return true;
			}
			return false;
		}

		@Override
		protected boolean tryRelease(int arg) {
			setState(arg);
			return true;
		}
	}

	private Syn syn = new Syn();

	@Override
	public void lock() {
		syn.acquire(1);
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {

	}

	@Override
	public boolean tryLock() {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		throw new UnsupportedOperationException();
	}

	@Override
	public void unlock() {
		syn.release(0);
	}

	@Override
	public Condition newCondition() {
		throw new UnsupportedOperationException();
	}

}
